import { Request, Response } from 'express';
import { messageService } from './service';
import { AuthRequest } from '../../types/auth';
import { ApiResponse } from '../../types/page';
import { MessageStatus, MessageType } from '../../entities/SystemMessage';

type MessageListResponse = {
  records: any[];
  total: number;
  size: number;
  current: number;
  pages: number;
  unreadCount: number;
};

/**
 * 获取用户消息列表
 */
export const getUserMessages = async (req: AuthRequest, res: Response) => {
  try {
    const current = Number(req.query.page) || 1;
    const size = Number(req.query.size) || 10;
    const userId = req.user?.id;
    
    if (!userId) {
      return res.status(401).json({
        success: false,
        message: '用户未登录'
      });
    }
    
    // 构造查询条件
    const queryParams: any = {
      page: current,
      pageSize: size
    };
    
    // 添加状态过滤
    if (req.query.status !== undefined) {
      queryParams.status = Number(req.query.status);
    }
    
    // 添加类型过滤
    if (req.query.type !== undefined) {
      queryParams.type = Number(req.query.type);
    }
    
    // 获取消息列表和未读消息数
    const [{ messages, total }, unreadCount] = await Promise.all([
      messageService.getUserMessages(queryParams),
      messageService.getUnreadCount(userId)
    ]);
    
    // 格式化响应数据
    const response: ApiResponse<MessageListResponse> = {
      success: true,
      data: {
        records: messages,
        total,
        size,
        current,
        pages: Math.ceil(total / size),
        unreadCount
      }
    };
    
    res.json(response);
  } catch (error: any) {
    res.status(500).json({
      success: false,
      message: '获取消息列表失败',
      error: error.message
    });
  }
};

/**
 * 获取消息详情并标记为已读
 */
export const getMessageDetail = async (req: AuthRequest, res: Response) => {
  try {
    const id = req.params.id;
    const userId = req.user?.id;
    
    if (!userId) {
      return res.status(401).json({
        success: false,
        message: '用户未登录'
      });
    }
    
    // 获取消息详情
    const message = await messageService.getMessageById(id);
    
    if (!message) {
      return res.status(404).json({
        success: false,
        message: '消息不存在'
      });
    }
    
    // 验证消息所属
    if (message.userId !== userId) {
      return res.status(403).json({
        success: false,
        message: '无权访问该消息'
      });
    }
    
    // 如果消息未读，标记为已读
    if (message.status === MessageStatus.UNREAD) {
      await messageService.markAsRead(id);
      message.status = MessageStatus.READ; // 更新返回的状态
    }
    
    res.json({
      success: true,
      data: message
    });
  } catch (error: any) {
    res.status(500).json({
      success: false,
      message: '获取消息详情失败',
      error: error.message
    });
  }
};

/**
 * 标记全部消息为已读
 */
export const markAllAsRead = async (req: AuthRequest, res: Response) => {
  try {
    const userId = req.user?.id;
    
    if (!userId) {
      return res.status(401).json({
        success: false,
        message: '用户未登录'
      });
    }
    
    await messageService.markAllAsRead(userId);
    
    res.json({
      success: true,
      message: '所有消息已标记为已读'
    });
  } catch (error: any) {
    res.status(500).json({
      success: false,
      message: '标记全部已读失败',
      error: error.message
    });
  }
};

/**
 * 删除消息
 */
export const deleteMessage = async (req: AuthRequest, res: Response) => {
  try {
    const id = req.params.id;
    const userId = req.user?.id;
    
    if (!userId) {
      return res.status(401).json({
        success: false,
        message: '用户未登录'
      });
    }
    
    const result = await messageService.deleteMessage(id);
    
    if (!result) {
      return res.status(404).json({
        success: false,
        message: '消息不存在或无权删除'
      });
    }
    
    res.json({
      success: true,
      message: '删除消息成功'
    });
  } catch (error: any) {
    res.status(500).json({
      success: false,
      message: '删除消息失败',
      error: error.message
    });
  }
};

/**
 * 批量删除消息
 */
export const batchDeleteMessages = async (req: AuthRequest, res: Response) => {
  try {
    const { ids } = req.body;
    const userId = req.user?.id;
    
    if (!userId) {
      return res.status(401).json({
        success: false,
        message: '用户未登录'
      });
    }
    
    if (!ids || !Array.isArray(ids) || ids.length === 0) {
      return res.status(400).json({
        success: false,
        message: '消息ID列表不能为空'
      });
    }
    
    const affectedCount = await messageService.batchDeleteMessages(ids);
    
    res.json({
      success: true,
      message: `成功删除${affectedCount}条消息`,
      data: { affectedCount }
    });
  } catch (error: any) {
    res.status(500).json({
      success: false,
      message: '批量删除消息失败',
      error: error.message
    });
  }
}; 